package com.ejlchina.tool.util

import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattService
import android.util.Log
import com.ejlchina.tool.constant.BLE_CHARACTER_INDICATE
import com.ejlchina.tool.constant.BLE_CHARACTER_WRITE
import com.ejlchina.tool.constant.BLE_SERVICE
import com.ejlchina.tool.constant.FIRMWARE_VERSION_PREFIX
import com.ejlchina.tool.constant.HARDWARE_VERSION_PREFIX
import com.huyuhui.fastble.BleManager
import com.huyuhui.fastble.data.BleDevice

class DeviceUtil {

    companion object{

        val serviceMap = hashMapOf<BleDevice,BluetoothGattService?>()
        val characteristicMap = hashMapOf<BleDevice,BluetoothGattCharacteristic?>()

        fun getVersionDesc(version: Int, isHardware: Boolean): String {
            val descPrefix = if (isHardware) HARDWARE_VERSION_PREFIX else FIRMWARE_VERSION_PREFIX
            val versionDesc = StringBuilder(descPrefix)
            var versionStr = version.toString()
            if (version < 10) {
                versionStr = "00$versionStr"
            }else if (version < 100) {
                versionStr = "0$versionStr"
            }
            if (isHardware) {
                for (i in versionStr.length - 1 downTo 0) {
                    versionDesc.append(versionStr[i])
                    if (i != 0) {
                        versionDesc.append(".")
                    }
                }
            }else{
                for (i in versionStr.indices) {
                    versionDesc.append(versionStr[i])
                    if (i != versionStr.length - 1) {
                        versionDesc.append(".")
                    }
                }
            }
            return versionDesc.toString()
        }

        fun getBleService(bleDevice: BleDevice): BluetoothGattService?{
            BleManager.getBluetoothGattServices(bleDevice)?.let {
                return it.find { serviceList ->  serviceList.uuid.toString().contains(BLE_SERVICE,true) }
            }
            return null
        }

        fun getBleWriteCharacteristic(bleDevice: BleDevice, isForFileUpload: Boolean = false): BluetoothGattCharacteristic?{
            getBleService(bleDevice)?.let {
                return it.characteristics.find { bluetoothGattCharacteristic ->
                    bluetoothGattCharacteristic.uuid.toString().contains(if (isForFileUpload) BLE_CHARACTER_WRITE  else BLE_CHARACTER_INDICATE,true) }
            } ?: kotlin.run {
                return null
            }
        }

        fun getBleReadCharacteristic(bleDevice: BleDevice): BluetoothGattCharacteristic?{
            getBleService(bleDevice)?.let {
                return it.characteristics.find { bluetoothGattCharacteristic ->
                    bluetoothGattCharacteristic.uuid.toString().contains(BLE_CHARACTER_INDICATE,true) }
            } ?: kotlin.run {
                return null
            }
        }
    }
}